package com.mohe.zhihui.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSON;

public class UploadImageServlet extends HttpServlet {

	private static final long serialVersionUID = -3059156381658548718L;

	public UploadImageServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String realPath = request.getSession().getServletContext().getRealPath("pics");// 当前WEB环境的上层目录
		if (request.getSession() == null) {// 如果用户没有登录，则不允许上传
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("error", 1);
			m.put("message", "请登录后再上传图片");
			response.getWriter().write(JSON.toJSONString(m));
		} else {
			File up = new File(realPath);
			if (!up.exists()) {
				up.mkdirs();
			}
			// 定义允许上传的文件扩展名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			String dirName = request.getParameter("dir");
			if (dirName == null) {
				dirName = "image";
			}
			response.setCharacterEncoding("UTF-8");
			String tempFileName = null;// 上传到服务器的临时文件名
			String newFileName = null;// 最后合并后的新文件名
			BufferedOutputStream outputStream = null;
			if (ServletFileUpload.isMultipartContent(request)) {
				try {
					DiskFileItemFactory factory = new DiskFileItemFactory();
					factory.setSizeThreshold(1024);
					ServletFileUpload upload = new ServletFileUpload(factory);
					upload.setHeaderEncoding("UTF-8");
					List<FileItem> items = upload.parseRequest(request);
					for (FileItem item : items) {
						if (!item.isFormField()) {// 是文本域
							tempFileName = item.getName();
							String fileExt = tempFileName.substring(tempFileName.lastIndexOf(".") + 1).toLowerCase();
							if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
								Map<String, Object> m = new HashMap<String, Object>();
								m.put("error", 1);
								m.put("message", "上传文件扩展名是不允许的扩展名");
								response.getWriter().write(JSON.toJSONString(m));
								return;
							}
							if (tempFileName != null) {
								newFileName = System.nanoTime() + "." + fileExt;
								File savedFile = new File(realPath, newFileName);
								item.write(savedFile);
							}
						}
					}

					Map<String, Object> m = new HashMap<String, Object>();
					m.put("error", 0);
					m.put("url", "/tmx/pics/" + newFileName);
					response.getWriter().write(JSON.toJSONString(m));
				} catch (FileUploadException e) {
					e.printStackTrace();
					Map<String, Object> m = new HashMap<String, Object>();
					m.put("error", 1);
					m.put("message", "上传失败");
					response.getWriter().write(JSON.toJSONString(m));
				} catch (Exception e) {
					e.printStackTrace();
					Map<String, Object> m = new HashMap<String, Object>();
					m.put("error", 1);
					m.put("message", "上传失败");
					response.getWriter().write(JSON.toJSONString(m));
				} finally {
					try {
						if (outputStream != null) {
							outputStream.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
